import {ref} from "vue"
import store from "@/store"
import {defineStore} from "pinia"
import {getRouteByApi} from "@/api/routes"
import {type RouteRecordRaw} from "vue-router"
import {constantRoutes, asyncRoutes} from "@/router"
const modules = import.meta.glob("@/views/*/*.vue")

const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => {
      if (route.meta?.roles !== undefined) {
        return route.meta.roles.includes(role)
      } else {
        return false
      }
    })
  } else {
    return true
  }
}

const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const res: RouteRecordRaw[] = []
  routes.forEach((route) => {
    const r = {...route}
    if (hasPermission(roles, r)) {
      if (r.children) {
        r.children = filterAsyncRoutes(r.children, roles)
      }
      res.push(r)
    }
  })
  return res
}

export const usePermissionStore = defineStore("permission", () => {
  const routes = ref<RouteRecordRaw[]>([])
  const dynamicRoutes = ref<RouteRecordRaw[]>([])

  const setRoutes = async (roles: string[]) => {
    let accessedRoutes: any[] = []
    // @ts-ignore
    await getRouteByApi(roles[0].id).then((res) => {
      // @ts-ignore
      const map = res.data.map((item) => {
        if (item.children.length > 0) {
          // @ts-ignore
          item.children.map((citem) => {
            citem.component = modules["/src/views/" + citem.componentStr] // () => import("@/views/" + citem.componentStr)
            return citem
          })
        }
        item.component = () => import("@/layout/index.vue")
        return item
      })
      accessedRoutes = map.concat(asyncRoutes)
    })
    routes.value = constantRoutes.concat(accessedRoutes)
    dynamicRoutes.value = accessedRoutes
  }

  return { routes, dynamicRoutes, setRoutes }
})

/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
